//
//  GrowthAppDelegate.m
//  Growth
//
//  Created by Hobo.Chen on 12/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GrowthAppDelegate.h"
#import"PublicMethodEngine.h"
#import "LocationEngine.h"

#import "WebRequest.h"

#import "NotificationEngine.h"

#import "LoginViewController.h"

#import "SettingViewController.h"

#import "LocaleDateVerifyClass.h"

#import "VersionUpdateClass.h"

#import "HospitalIntroductionViewController.h"

@interface GrowthAppDelegate (Private)

-(void)copyDatabase;
-(BOOL)saveData:(NSData *)data fileName:(NSString *)fileName;
-(NSString *)dataFilePath:(NSString *)fileName;

@end


@implementation GrowthAppDelegate

@synthesize window;


@synthesize firstController;




@synthesize loadingView;


//第三方
//QQ
@synthesize qqAppKey;
@synthesize qqAppSecret;
@synthesize qqTokenKey;
@synthesize qqTokenSecret;
@synthesize qqVerifier;
@synthesize qqResponse;

//Sina
@synthesize sinaAppKey;
@synthesize sinaAppSecret;
@synthesize sinaTokenKey;
@synthesize sinaTokenSecret;
@synthesize sinaVerifier;
@synthesize sinaResponse;
@synthesize sinaUserId;

#pragma mark -
#pragma mark Application lifecycle


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
    
    CLog(@"application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOption");
    
   // self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    
    //取消所有Notification
    [[NotificationEngine sharedNotificationEngine] removeNotification];
    
    //网络监听
    [NetworkEngine sharedNetworkEngine];
    
  
	
	PublicMethodEngine *methodEngine = [PublicMethodEngine sharedPublicMethodEngine];
	[methodEngine createFolder:@"image"];
	
		  
        
    // Let the device know we want to receive push notifications
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    
    
    //根据不同角色加载不同模块
    int role = 1;
    if ([[NSUserDefaults standardUserDefaults] valueForKey:ROLE]) {
        role = [[[NSUserDefaults standardUserDefaults] valueForKey:ROLE] intValue];
    }
 
    if (role ==1) {
        
        UIViewController *viewContr = [[HospitalIntroductionViewController alloc]init];
        self.firstController = viewContr;
        [viewContr release];
        
        /**
        self.firstController = [[UploadDataViewController alloc] init];
        UINavigationController * firstNav = [[UINavigationController alloc] initWithRootViewController:self.firstController];
        
       
        self.secondController = [[ForumMainViewViewController alloc] init];
        UINavigationController * secondNav = [[UINavigationController alloc] initWithRootViewController:self.secondController];
        
        
        self.thirdController = [[ForumPostDetailViewController alloc] init];
        UINavigationController * thirdNav = [[UINavigationController alloc] initWithRootViewController:self.thirdController];
        
      
        self.forthController = [[BlogMainViewViewController alloc] init];
        UINavigationController *forthNav = [[UINavigationController alloc] initWithRootViewController:forthController];
        
        self.fifthController = [[SettingViewController alloc] init];
        UINavigationController *fifthNav = [[UINavigationController alloc] initWithRootViewController:fifthController];
        
        NSArray *ctrlArr = [NSArray arrayWithObjects:firstNav,secondNav,thirdNav,forthNav,fifthNav,nil];
        [firstNav release];
        [secondNav release];
        [thirdNav release];
        [forthNav release];
        [fifthNav release];
        
        
        self.tabBarController.delegate = self;
        self.tabBarController.viewControllers = ctrlArr;
         
         **/
     
    }
    else{
        
        UIViewController *viewContr = [[HospitalIntroductionViewController alloc]init];
        self.firstController = viewContr;

        [viewContr release];
        
        /**
        self.firstController = [[UnreadOrdersViewController alloc] init];
        UINavigationController * firstNav = [[UINavigationController alloc] initWithRootViewController:self.firstController];
        firstNav.navigationBar.tintColor = [UIColor blackColor];
        
        
        self.secondController = [[HaveReadOrdersViewController alloc] init];
        UINavigationController * secondNav = [[UINavigationController alloc] initWithRootViewController:self.secondController];
          secondNav.navigationBar.tintColor = [UIColor blackColor];
        
        self.thirdController = [[TransferToCenterViewController alloc] init];
        UINavigationController * thirdNav = [[UINavigationController alloc] initWithRootViewController:self.thirdController];
         thirdNav.navigationBar.tintColor = [UIColor blackColor];
        
        self.forthController = [[BlogMainViewViewController alloc] init];
        UINavigationController *forthNav = [[UINavigationController alloc] initWithRootViewController:forthController];
         forthNav.navigationBar.tintColor = [UIColor blackColor];
        self.fifthController = [[SettingViewController alloc] init];
        UINavigationController *fifthNav = [[UINavigationController alloc] initWithRootViewController:fifthController];
        fifthNav.navigationBar.tintColor = [UIColor blackColor];
        NSArray *ctrlArr = [NSArray arrayWithObjects:firstNav,secondNav,thirdNav,forthNav,fifthNav,nil];
        [firstNav release];
        [secondNav release];
        [thirdNav release];
        [forthNav release];
        [fifthNav release];
        
        self.tabBarController.delegate = self;
        self.tabBarController.viewControllers = ctrlArr;
         
         **/
        
    }
   
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self.firstController];
    
    [self.window setRootViewController:nav];
    
    [nav release];
    
    [self.window makeKeyAndVisible];

    //Loading View
	loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
	loadingView.center = CGPointMake(160, 240);
	[loadingView setBackgroundColor:[UIColor clearColor]];
	//[loadingView setAlpha:0.3];
	[loadingView setMultipleTouchEnabled:NO];
	[loadingView setUserInteractionEnabled:NO];
	
	//[self.window insertSubview:loadingView atIndex:kTopViewIndex+100];
    [self.window addSubview:loadingView];
    

    //测试，默认已登录
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:USER_ID];
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:2] forKey:ROLE];
    
    
    if (![[NSUserDefaults standardUserDefaults] valueForKey:USER_ID]) {
        
        LoginViewController *con = [[LoginViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:con];
      
        [self.firstController presentViewController:nav animated:YES completion:nil];
        [con release];
        [nav release];
        
    }
    
    
      return YES;
}


- (void)reloadTabBarController{
    

       
    int role = 1;
    if ([[NSUserDefaults standardUserDefaults] valueForKey:ROLE]) {
        role = [[[NSUserDefaults standardUserDefaults] valueForKey:ROLE] intValue];
    }
    
    if (role ==1) {
        
        UIViewController *viewContr = [[HospitalIntroductionViewController alloc]init];
        self.firstController = viewContr;
        
        [viewContr release];

    }
    else{
        
        UIViewController *viewContr = [[HospitalIntroductionViewController alloc]init];
        self.firstController = viewContr;
        
        [viewContr release];

    }
    
   

}


#pragma 版本更新
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) {
        
        NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/app/id%@?mt=8",@"525681769"];  
        
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        
    }
    
    
}


- (UIView *)getLoadingView 
{
	[self.window bringSubviewToFront:self.loadingView];
	return self.loadingView;
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken 
{
    
    NSString *deviceTokenStr = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    
    CLog(@"Device token str %@", deviceTokenStr);
    [[NSUserDefaults standardUserDefaults] setValue:deviceTokenStr forKey:DEVICE_TOKEN_KEY];
    
    [[NotificationEngine sharedNotificationEngine] postDeviceToken];
    
    
    
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    CLog(@"Failed to get token, error: %@", error);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //    NSString *infoStr = [NSString stringWithFormat:@"%@", userInfo];
    //    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Dict" message:infoStr delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
    //
    //    
    //    [alertView show];
    //    [alertView release];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    CLog(@"DidReceiveLocalNotification");
    
    [[NotificationEngine sharedNotificationEngine] removeNotification];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    CLog(@"EnterBackground!");
    
    NotificationEngine *engine = [NotificationEngine sharedNotificationEngine];
    
    //[engine plansNotification];
    [engine recordRemindNotification];
   
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
    CLog(@"EnterForeground!");
    
    //版本检测
//    VersionUpdateClass *versionUpdateClass  = [VersionUpdateClass shareVersionUpdateClass];
//    [versionUpdateClass VersionUpdateMethord ];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    //地理位置
    [LocationEngine sharedLocationEngine].locationState = @"Error";
    
    
    //取消所有Notification
    [[NotificationEngine sharedNotificationEngine] removeNotification];
    
       CLog(@"BecomeActive!");
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
      CLog(@"Terminate!");
    
}


#pragma mark -
#pragma mark 系统版本验证清空旧数据
- (void)localeVersionCheck
{
    NSString *localeVersion = [[NSUserDefaults standardUserDefaults] valueForKey:GROWTH_LOCALE_VERSION_KEY];
    
    //关闭新版本更新后清空用户登陆信息，因为注册为填密码会出现用户无法再进入问题
    return;
    
    //在本地不是当前版本的情况下清空数据
    if (localeVersion == nil || ![localeVersion isEqualToString:VERSION]) {
        //删除安全验证信息
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Ucenter-Code"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Ucenter-VerifyCode"];
        
        //删除个人信息
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userName"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userAttachmentId"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:QQOpenId];
        
        //删除宝宝信息
        if ([[NSUserDefaults standardUserDefaults] valueForKey:BABY_ATTACHMENTID]) {
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:BABY_ATTACHMENTID];
        }
        
        if ([[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"]) {
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"timelineId"];
        }
        
        
        if ([[NSUserDefaults standardUserDefaults] valueForKey:BABYINFO]) {
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:BABYINFO]; 
            
        }
        
        [[NSUserDefaults standardUserDefaults] setValue:VERSION forKey:GROWTH_LOCALE_VERSION_KEY];
    }
}

#pragma mark -
#pragma mark MainView

#pragma mark -
#pragma mark Database Create
//将项目db文件拷贝到Documents文件夹下，以实现db可写
-(void)copyDatabase
{
	//做一个静态存储，不用每次尝试copy
	
    NSString *path=[NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],@"/databaseunco.sqlite3"];
    
    
	//NSLog(@"Path %@", path);
	
    NSData *databaseData = [NSData dataWithContentsOfFile:path];
    
    BOOL existed = [self saveData:databaseData fileName:kDatabaseName];
	
	CLog(@"database is exist %d!", existed);
}

-(BOOL)saveData:(NSData *)data fileName:(NSString *)fileName
{
    NSString *filePath = [self dataFilePath:fileName];
	NSLog(@"%@", filePath);
	if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        [data writeToFile:filePath atomically:YES];
        [[NSUserDefaults standardUserDefaults] setValue:VERIFY_LOCALE_DATABASE_VERSION forKey:VERIFY_LOCALE_DATABASE_KEY];
		return NO;
    }
	else{
        NSString *localeDatabaseVersion = [[NSUserDefaults standardUserDefaults] valueForKey:VERIFY_LOCALE_DATABASE_KEY];
        if (localeDatabaseVersion == nil || ![localeDatabaseVersion isEqualToString:VERIFY_LOCALE_DATABASE_VERSION]) {
            
            BOOL success = [[PublicMethodEngine sharedPublicMethodEngine] deleteFileWith:filePath];
            if (!success) {
                CLog(@"Delete old database error!!!!!!!");
            }
            [data writeToFile:filePath atomically:YES];
            
            [[NSUserDefaults standardUserDefaults] setValue:VERIFY_LOCALE_DATABASE_VERSION forKey:VERIFY_LOCALE_DATABASE_KEY];
        }
        else {
            
        }
        return YES;
    }
	
}


-(NSString *)dataFilePath:(NSString *)fileName
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	
	return [documentsDirectory stringByAppendingPathComponent:fileName];
	
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
    
    [firstController release];
    
        [super dealloc];
}



//test
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    if ([[url scheme] compare:@"heart"] == NSOrderedSame) {
        return YES;
    }
    return  NO;
}



@end
